package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;
    @Autowired
    WmNewsMapper wmNewsMapper;
    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());

        if(StringUtils.isNotBlank(dto.getTitle())){
            //  concat(%,?,%)
            dto.setTitle("%"+dto.getTitle()+"%");
        }

        //2.分页查询
        List<WmNewsVO> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }

    /**
     * 查询所有自媒体文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //1 参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2 条件封装执行查询
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        // 文章标题模糊查询
        wrapper.like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
        // 频道id
        wrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        // 文章状态
        wrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        // 发布时间 >= 开始时间
        wrapper.ge(dto.getBeginPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate());
        // 发布时间 <= 开始时间
        wrapper.le(dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate());
        // 当前自媒体人文章
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmNews::getUserId, user.getId());
        // 按照创建日期倒序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        // 分页条件构建
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //3 执行查询
        IPage<WmNews> pageResult = page(page, wrapper);
        //4 返回封装查询结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        result.setData(pageResult.getRecords());
        // 处理文章图片 
        result.setHost(webSite);
        return result;
    }
@Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        WmNews wmNews = parseDtoToWmNews(dto);
        saveWmNews(wmNews);
        // 如果是草稿  直接返回

        // TODO 3.1 抽取文章中关联的图片路径
        List<String> materialUrl = parseContentImages(wmNews.getContent());
        if (!CollectionUtils.isEmpty(materialUrl)){

        // TODO 3.2 关联文章内容中的图片和素材关系
        saveRelativeInfo(materialUrl, wmNews, WemediaConstants.WM_CONTENT_REFERENCE);

        // TODO 3.3 关联文章封面中的图片和素材关系  封面可能是选择自动或者是无图
        saveRelativeInfoCover(materialUrl, wmNews, dto);
        }

        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送 待审核消息 ==> 队列:{}, 文章id:{}",NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());

        return ResponseResult.okResult();
    }

@Autowired
    WmNewsAutoScanService wmNewsAutoScanService;
    @Override
    public ResponseResult findById(String id) {
        if (StringUtils.isBlank(id)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        WmNews news = this.getById(id);
        if (news == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章不存在");

        }
        ResponseResult result = ResponseResult.okResult(news);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult deleteNewsById(String id) {
        if (StringUtils.isBlank(id)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "数据不存在");
        }
        WmNews news = getById(id);
        if (news == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "数据不存在");
        }
        boolean b = removeById(id);
        if (!b) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "删除失败");
        }

        int delete = wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getNewsId, news.getId()));
        if (delete == 0) {
            System.out.println("fall");
        } else {
            System.out.println("success");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult downOrUpNews(WmNewsDTO dto) {
        if (StringUtils.isBlank(dto.getEnable().toString()) || StringUtils.isBlank(dto.getId().toString())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmNews news = getById(dto.getId());
        if (news == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        news.setEnable(dto.getEnable());
        boolean b = updateById(news);
        if (b == false) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "修改失败");
        }
        if (news.getArticleId()!=null) {
            if(news.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
                // 上架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,news.getArticleId());
            }else {
                // 下架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,news.getArticleId());
            }
        }
        return ResponseResult.okResult();
    }
@Autowired
    WmUserMapper wmUserMapper;
    @Override
    public ResponseResult findWmNews(Integer id) {
        if (id==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"id不存在");
        }
        WmNews news = getById(id);
        if (news==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章不存在");
        }
        WmUser user=null;
        if (news.getUserId()!=null){
             user = wmUserMapper.selectById(news.getUserId());

        }
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(news,wmNewsVo);
        if (wmNewsVo!=null){
            wmNewsVo.setAuthorName(user.getName());
        }
        ResponseResult result = new ResponseResult();
        result.setHost(webSite);
        return result.okResult(wmNewsVo);

    }

    @Override
    public ResponseResult authPass(NewsAuthDTO dto) {
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        wmNews.setStatus((short)4);
        if (dto.getMsg()!=null){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        //5. 通知定时发布文章
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult authFail(NewsAuthDTO dto) {
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(dto.getId());
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        wmNews.setStatus((short)2);
        if (dto.getMsg()!=null){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void saveRelativeInfoCover(List<String> materialUrl, WmNews wmNews, WmNewsDTO dto) {
        List<String> images = dto.getImages();
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            int size = materialUrl.size();
            if (size == 0) {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);

            } else if (size <= 2) {
                images = materialUrl.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else {

                images = materialUrl.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);

            }
            if (images != null) {
                wmNews.setImages(imageListToStr(images));
            }
            this.updateById(wmNews);
        }
        //保存封面关联关系
        if (!CollectionUtils.isEmpty(images)) {
            images = images.stream().map(url -> url.replaceAll(webSite, "")).collect(Collectors.toList());
            saveRelativeInfo(images, wmNews, WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    /**
     *
     */
    private void saveRelativeInfo(List<String> materialUrl, WmNews wmNews, Short type) {
        WmUser user = WmThreadLocalUtils.getUser();
//        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
//                .eq(WmMaterial::getUserId, user.getId())
//                .in(WmMaterial::getUrl, materialUrl)
//                .select(WmMaterial::getId));
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(materialUrl, user.getId());
        if (ids.size() < materialUrl.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "素材缺失");
        }
//        for (WmMaterial wmMaterial : wmMaterials) {
//            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
//            wmNewsMaterial.setMaterialId(wmMaterial.getId());
//            wmNewsMaterial.setNewsId(wmNews.getId());
//            wmNewsMaterial.setType(type);
//            wmNewsMaterialMapper.insert(wmNewsMaterial);
//        }
        wmNewsMaterialMapper.saveRelations(ids, wmNews.getId(), type);
    }

    private List<String> parseContentImages(String content) {
        List<Map> mapList = JSON.parseArray(content, Map.class);
        for (Map map : mapList) {
            if (map.get("type").equals("text")) {
                return null;
            }
        }
        return mapList.stream()
                .filter(x -> x.get("type").equals("image"))
                .map(x -> String.valueOf(x.get("value")))
                .map(url -> url.replaceAll(webSite, ""))
                .collect(Collectors.toList());
    }

    private WmNews parseDtoToWmNews(WmNewsDTO dto) {
        if (StringUtils.isBlank(dto.getContent()) || StringUtils.isBlank(dto.getTitle())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章标题和内容不能为空");
        }
        // 校验是否登陆
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "请先登录");
        }
        // 2 保存或修改文章
        WmNews wmNews = new WmNews();
        // 将dto参数里面的值设置到wmNews
        BeanUtils.copyProperties(dto, wmNews);
        //如果文章布局是自动，需要设置为null
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        // 处理dto参数 images封面集合 转换成 字符串
        if (!CollectionUtils.isEmpty(dto.getImages())) {
            String images = imageListToStr(dto.getImages());
            wmNews.setImages(images);
        }
        wmNews.setUserId(user.getId());
        return wmNews;
    }

    private String imageListToStr(List<String> images) {
        return images.stream()  // 获取流
                .map((url) -> url.replaceAll(webSite, ""))  // 对流数据的中间操作
                .collect(Collectors.joining(","));
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    WmMaterialMapper wmMaterialMapper;

    /**
     * 保存或修改文章
     *
     * @param wmNews 文章对象（前端传递）
     */
    private void saveWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP); // 上架
        if (wmNews.getId() == null) { // 保存操作
            save(wmNews);
        } else {  // 修改
            // 当前文章 和 素材关系表数据删除
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }

}